<template>
  <div class="subcontract-registration-manage">
    <div class="model-title-css">
      <div>安全管理文件</div>
    </div>
    <div class="background_wrap public-flex-row">
      <div class="left-box WholeScroll">
        <el-tree class="Public-Tree-Class" :data="leftList" :props="defaultProps" ref='treeData' node-key="oneKey" :highlight-current='true' :default-expanded-keys="defaultTreeKey" @node-click="handleNodeClick"></el-tree>
      </div>
      <div class="right-box">
        <div class="operate_wrap flex">
          <div class="flex-center">
          </div>
          <div class="flex-right-action-group" v-if="search.projectId && search.companyId">
            <el-button type="primary" size="small" class="add buildButtonStyle" round @click="handleClickDeal('build', { pid: 0 })"><i class="iconfont icon-icon_add"></i> 新增根目录
            </el-button>
            <el-button type="primary" size="small" class="delete buildButtonStyle" :loading="isLoading" round @click="getInitSafeFile"> 初始化目录
            </el-button>
          </div>
        </div>
        <div class="list_wrap">
          <el-table :key="tableKey" :border="true" :row-class-name="tableRowStyleName" :cell-class-name="cellClassFun" :header-cell-class-name="tableHeaderCellStyleName" :stripe="true" ref="multipleTable" :data="list" tooltip-effect="dark" row-key="id" style="width: 100%; font-family: PingFangSC-Regular; font-size: 14px" :tree-props="{ children: 'children' }" :span-method="arraySpanMethod" height="720px" :expand-row-keys="tableExpandKeys" @cell-click="cellClick">
            <el-table-column show-overflow-tooltip prop="name" label="安全管理文件目录">
            </el-table-column>
            <el-table-column show-overflow-tooltip width="80" prop="number" label="文件数" align="center">
            </el-table-column>
            <el-table-column show-overflow-tooltip width="200" label="操作" align="center">
              <template slot-scope="scope">
                <template v-if="scope.row.level == 1">
                  <el-button type="text" class="text-btn redColor" @click="handleClickDeal('deleteRoot', { number: scope.row.number, ids: scope.row.id })">删除</el-button>
                  <el-button type="text" class="text-btn" @click="handleClickDeal('edit', { id: scope.row.id, name: scope.row.name })">编辑</el-button>
                  <el-button type="text" class="text-btn" @click="handleClickDeal('build', { pid: scope.row.id })">加子目录</el-button>
                </template>
                <template v-else-if="scope.row.level == 2">
                  <el-button type="text" class="text-btn redColor" @click="handleClickDeal('deleteRoot', { number: scope.row.number, ids: scope.row.id })">删除</el-button>
                  <el-button type="text" class="text-btn" @click="handleClickDeal('edit', { id: scope.row.id, name: scope.row.name })">编辑</el-button>

                  <el-button :loading="scope.row.isLoading" type="text" class="text-btn">
                    <el-upload style="display: flex;" :before-upload="(file) => uploadPartOne(file, scope.row)" action :multiple="false" :show-file-list="false">上传文件
                    </el-upload>
                  </el-button>
                </template>
                <template v-else-if="scope.row.level == 3">
                  <el-button type="text" class="text-btn redColor" @click="removeFile(scope.row)">删除</el-button>
                  <el-button type="text" class="text-btn" @click="download(scope.row)">下载</el-button>
                  <el-button type="text" class="text-btn" @click="handleClickDeal('fileMove', { file: scope.row })">移动文件</el-button>
                </template>
              </template>
            </el-table-column>

          </el-table>
        </div>
      </div>
    </div>
    <el-dialog width="30%" :visible.sync="rootDialog.show" @close="handleClickDeal('cancel')" v-dialog-drag :modal-append-to-body="false" :close-on-click-modal="false">
      <span slot="title">
        <i class="iconfont icon-rizhi"></i>
        <span>{{ rootDialog.typeName }}</span>
      </span>
      <el-form :model="formBaseData" ref="formBaseData" :rules="formBaseRules" class="measurepaycompensation_detail_form">
        <template v-if="rootDialog.type == 'edit' || rootDialog.type == 'build'">
          <el-row>
            <el-col :span="24">
              <el-form-item class="" label="目录名称" prop="name" label-width="140px">
                <el-input style="width: 100%;" size="small" v-model="formBaseData.name" placeholder=""></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </template>
        <template v-if="rootDialog.type == 'fileMove'">
          <el-row>
            <el-col :span="24">
              <el-form-item class="" label="目录" prop="directory" label-width="140px">
                <el-cascader style="width: 100%;" :props="{ value: 'id', label: 'name', }" v-model="formBaseData.directory" :options="listOptions"></el-cascader>
              </el-form-item>
            </el-col>
          </el-row>
        </template>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <template>
          <el-button size="small" type="primary" :loading="isLoading" @click="handleClickDeal('submit')">
            <i class="iconfont icon-icon_save"></i> 确 定</el-button>
        </template>
        <el-button size="small" @click="handleClickDeal('cancel')"><i class="iconfont icon-icon_cancel"></i> 取
          消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  tableRowStyleGol,
  tableCellStyleGol,
  tableHeaderCellStyleGol,
} from '@/utils/publicFun'
import msgUtil from '@/utils/msgUtil'
import safeArrangeFileApi from '@/api/buss/safeArrangeFile'
import publicSearchData from '@/mixins/publicSearchData'
export default {
  name: `security-management-document`,
  mixins: [publicSearchData],
  data() {
    return {
      leftList: [],
      defaultTreeKey: [],
      defaultProps: {
        children: 'children',
        label: 'name',
      },
      chooseTreeData: {},
      permission: {
        add: ['100', 'imageProgressBreak:add'],
        show: ['100', 'imageProgressBreak:show'],
        edit: ['100', 'imageProgressBreak:edit'],
        del: ['100', 'imageProgressBreak:del'],
      },

      tableRowStyleName: tableRowStyleGol,
      tableCellStyleName: tableCellStyleGol,
      tableHeaderCellStyleName: tableHeaderCellStyleGol,
      tablePaginationPrev: '上一页',
      tablePaginationNext: '下一页',
      isLoading: false,
      list: [
      ],
      // 搜索参数
      search: {
        projectId: '',
        companyId: ''
      },
      formBaseRules: {
        name: [
          { required: true, message: '请输入' + '目录名称', trigger: 'blur' },
        ],
        directory: [
          { required: true, message: '请选择' + '目录', trigger: 'blur' },
        ],
      },
      formBaseData: {
        name: '',
        pid: '',
        directory: '',
        id: '',
        fileId: '',
      },
      rootDialog: {
        show: false,
        type: 'build'
      },
      fileSystem: {
        attachId: '',
        sys: 'buss',
        module: 'safeArrangeFile',
        part: 'one',
      },
      tableKey: 999,
      tableExpandKeys: [],
      listOptions: []
    }
  },
  watch: {
    list(val) {
      this.listOptions = val.map(item => {
        let temp = JSON.parse(JSON.stringify(item))
        temp.children && temp.children.forEach(item2 => {
          delete item2.children
        })
        return temp
      })
    }
  },
  mounted() {
    this.initData()
  },
  methods: {
    initData() {
      safeArrangeFileApi.getProjectCompanyTree().then(res => {
        if (res.code === 200) {
          res.data.forEach(item => {
            item.level = 1
            item.oneKey = item.id
            item.children && item.children.forEach(item2 => {
              item2.level = 2
              item2.projectId = item.id
              item2.oneKey = item.id + item2.id
            })
          });
          this.$set(this, 'leftList', res.data)
          this.$nextTick(() => {
            if (this.$headerSearch) {
              console.log(this.changeHeaderProject, '888');
              if (this.changeHeaderProject) {
                this.$refs['treeData'].setCurrentKey(this.changeHeaderProject);
                if (this.defaultTreeKey) {
                  this.defaultTreeKey.push(this.changeHeaderProject)
                }
                this.handleNodeClick({
                  id: this.changeHeaderProject,
                  level: '1'
                })
              } else {
                this.defaultTreeKey.push(this.leftList[0].id)
                this.$refs['treeData'].setCurrentKey(this.leftList[0].id);
                if (this.defaultTreeKey) {
                  this.defaultTreeKey.push(this.leftList[0].id)
                }
                this.handleNodeClick(this.leftList[0])
              }
            } else {
              this.defaultTreeKey.push(this.leftList[0].id)
              this.$refs['treeData'].setCurrentKey(this.leftList[0].id);
              if (this.defaultTreeKey) {
                this.defaultTreeKey.push(this.leftList[0].id)
              }
              this.handleNodeClick(this.leftList[0])
            }
          })
        } else {
          this.$messageError(res.data.message)
        }
      }).catch((res) => {
        console.error(res)
        this.$messageError('获取失败')
      })
    },
    getInitSafeFile() {
      if (!this.search.projectId || !this.search.companyId) {
        this.$messageError('请选择项目与单位')
        return
      }
      this.isLoading = true
      safeArrangeFileApi.getInitSafeFile(this.search).then(res => {
        this.getList()
      }).catch(err => {
        console.log(err);
      }).finally((res) => {
        this.isLoading = false
      })
    },
    // 事件处理的api请求
    sealDealHttp(url, query, param, callback) {
      this.$httpPost(url + query, param)
        .then((res) => {
          if (res.status === 1) {
            if (callback) callback(res)
            // 重新获取数据
            setTimeout(() => {
              this.getList()
            }, 1000)
          } else {
            this.$messageError(res.message)
          }
        })
        .catch((res) => {
          console.log('请求出现错误', res)
          console.log(res)
        })
    },
    handleNodeClick(data) {
      console.log(data, 'data 22');
      if (data.level == 2) {
        this.search.projectId = data.projectId
        this.search.companyId = data.id
        this.getList()
      } else if (data.level == 1) {
        this.search.projectId = data.id
        this.search.companyId = ''
        this.list = []
      }

    },
    cellClassFun({ row, column, rowIndex, columnIndex }) {
      if ((row.level == 3 && columnIndex === 0) || (row.level == 2 && columnIndex === 1)) {
        return 'tableRowStyleCss blue-btn'
      } else {
        'tableRowStyleCss'
      }
    },
    // 获取列表 api
    getList() {
      safeArrangeFileApi.getTree(this.search.companyId, this.search.projectId).then((res) => {
        if (res.code === 200) {
          this.list = []
          this.list = res.data;
          this.deffTree(this.list, (item, parentItem) => {
            item.level == 1 && this.tableExpandKeys.push(item.id)
          })
          // this.list.forEach(item => {
          //   this.tableExpandKeys.push(item.id)
          //   item.children && item.children.forEach(item2 => {
          //     this.tableExpandKeys.push(item2.id)
          //     item2.parentId = item.id
          //   })
          // })
          this.$forceUpdate()
        } else {
          this.$messageError(res.data.message)
        }
      })
        .catch((res) => {
          console.log('请求出现错误', res)
          this.$messageError('请求失败')
        })
    },
    deffTree(data, callback, parentItem) {
      data.map(item => {
        if (callback) callback(item, parentItem)
        if (item.children) {
          this.deffTree(item.children, callback, item);
        }
      });
    },
    arraySpanMethod({ row, column, rowIndex, columnIndex }) {
      if (row.level == 3) {
        if (columnIndex === 0) {
          return [1, 2];
        } else if (columnIndex === 1) {
          return [0, 0];
        }
      }
    },
    // 点击各个流程的按钮事件
    handleClickDeal(type, params) {


      switch (type) {
        // 取消，关闭窗口
        case 'cancel':
          this.rootDialog.show = false
          this.$refs['formBaseData'].resetFields()
          this.formBaseData = {
            name: '',
            pid: '',
            directory: ''
          }
          break
        case 'build':
          this.rootDialog = {
            show: true,
            type: type,
            typeName: '新增目录',
            params
          }
          this.formBaseData.pid = params.pid
          break
        case 'edit':
          this.rootDialog = {
            show: true,
            type: type,
            typeName: '编辑目录',
            params
          }
          this.formBaseData.name = params.name
          this.formBaseData.id = params.id
          break
        case 'fileMove':
          this.rootDialog = {
            show: true,
            type: type,
            typeName: '移动目录',
            params
          }
          this.formBaseData.fileId = params.file.id
          break
        case 'submit':
          this.$refs['formBaseData'].validate((valid) => {
            if (valid) {
              // 再验证其他内容
              // 整理文件信息
              this.isLoading = true
              if (this.rootDialog.type == 'fileMove') {
                console.log("文件", this.rootDialog.params.file)
                console.log("目录", this.formBaseData.directory)
                this.formBaseData.id = this.formBaseData.directory[1]
                this.moveFileSave(() => {
                  this.isLoading = false
                  this.getList()
                  this.$notify({
                    title: '移动完成',
                    type: 'success',
                    duration: 1500
                  })
                })
              } else {
                // 提交详情
                this.submitDetail(() => {
                  this.isLoading = false
                  this.getList()
                  this.$notify({
                    title: '保存成功',
                    type: 'success',
                    duration: 1500
                  })
                })
              }

            }
          })
          break
        case 'deleteRoot':
          let msg = '确认删除该目录吗?'
          if (params.number > 0) {
            msg = '该目录下已经上传了文件，删除该目录，相应的文件也将删除，确认删除吗?'
          }
          msgUtil.confirm(msg).then(res => {
            let param = {
              ids: params.ids.split(',')
            }
            safeArrangeFileApi.del(param).then(res => {
              if (res.code === 200) {
                msgUtil.success2('删除成功!')
                this.getList()
              } else {
                msgUtil.error2(res.data.message)
              }
            })
          })
          break
      }
    },
    submitDetail(callback) {
      let api = safeArrangeFileApi.submit
      if (this.rootDialog.type == 'edit') {
        api = safeArrangeFileApi.resubmit
      }
      api({
        ...this.formBaseData,
        ...this.search
      }).then(res => {
        if (res.code === 200) {
          this.rootDialog.show = false
          if (callback) callback()
        } else {
          msgUtil.error2(res.data.message)
        }
      }).catch((res) => {
        console.log(res)
      }).finally((response) => {
        this.isLoading = false
      })
    },
    moveFileSave(callback) {
      let api = safeArrangeFileApi.moveFile

      api({
        ...this.formBaseData,
      }).then(res => {
        if (res.code === 200) {
          this.rootDialog.show = false
          if (callback) callback()
        } else {
          msgUtil.error2(res.data.message)
        }
      }).catch((res) => {
        console.log(res)
      }).finally((response) => {
        this.isLoading = false
      })
    },
    uploadPartOne(file, item) {
      this.$set(item, 'isLoading', true)
      this.$store.state.settings.uploadLoading = false
      this.$publicUpload.uploadFile(file, item.id, this.fileSystem.module, this.fileSystem.part, file.name).then(async res => {
        if (res.code === 200) {
          this.getList()
        } else {
          msgUtil.error2(res.data.message)
        }
      }).catch(res => {
        this.$set(this, 'isLoading', false)
        this.$store.state.settings.uploadLoading = true
        msgUtil.error2('上传文件前-请求失败!')
      }).finally(() => {
        this.$set(this, 'isLoading', false)
        this.$store.state.settings.uploadLoading = true
      })
    },
    // 删除文件时解绑文件
    removeFile(file) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await this.$publicUpload.removeFile(file.id)
        this.getList()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    download(file) {
      this.$publicUpload.checkFile(file.id, file.name)
    },
    cellClick(row, column, cell, event) {
      if (row.level == 3 && column.property == 'name') {
        this.$httpGet('/file-server/file/preview?id=' + row.id).then(response => {
          this.loading = false;
          //  如果是minio地址路径，则调用kkview
          if (!response.data.startsWith("/")) {
            window.open(PREVIEW_URL + '/onlinePreview?url=' + encodeURIComponent(Base64.encode(response.data)));
          } else {
            //  如果是转换后的previewGetFile，浏览器直接打开
            window.open(response.data);
          }
        }).catch(res => {
          this.loading = false;
        })

      } else if (row.level == 2 && column.property == 'number') {
        if (row.number <= 0) {
          this.$messageWarning('该目录下没有文件')
          return
        }
        this.$refs.multipleTable.toggleRowExpansion(row)
        // this.tableKey++
      }
    },
  },
}
</script>

<style scoped lang="scss">
.model-title-css {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
}

.list_wrap {
  margin-top: 20px;
}

.left-box {
  min-width: 300px !important;
  max-width: 350px !important;
  max-height: calc(100vh - 200px);
  border-right: 1px #e2e8ec solid;
  overflow: auto;

  p {
    cursor: pointer;
    font-size: 14px;
  }
}

.right-box {
  width: calc(100% - 300px);
  padding-left: 15px;
  flex-grow: 1;
}

.text-btn {
  font-size: 15px;
}

.redColor {
  color: #fa373c !important;
}

::v-deep .blue-btn {
  color: #3270ef !important;
  cursor: pointer;
  background: transparent;

  &:hover {
    text-decoration: underline;
    color: #005fff !important;
  }
}
</style>

